package org.beetl.json.node;

import java.io.IOException;
import java.util.List;
import java.util.TreeSet;

import org.beetl.json.ActionComparator;
import org.beetl.json.ActionReturn;
import org.beetl.json.JsonWriter;
import org.beetl.json.Location;
import org.beetl.json.LocationAction;
import org.beetl.json.OutputNode;
import org.beetl.json.action.IValueAction;

public class JavaObjectNode implements OutputNode {

	protected  TreeSet<IValueAction>  valueActions =  new TreeSet(new ActionComparator<IValueAction>());
	Class c ;
	public JavaObjectNode(Class c){
		this.c = c ;
	}
	@Override
	public void render(Object obj, JsonWriter w) throws IOException {
	
	
		if(this.valueActions.size()!=0){			
			for(IValueAction valueAction:this.valueActions){
				ActionReturn ar = valueAction.doit(obj, this);	
				obj = ar.value;
				if(!ar.process){
					break ;
				}				
			}
								
		}
		
		w.write(obj);
		

	}

	@Override
	public void setActionByLocation(List<Location> list) {
		for(Location l:list){			
			LocationAction action = l.getAction();
				 if(action instanceof IValueAction){		
					 if(isMatch(l)){						 
						 this.valueActions.add( (IValueAction)action);
					 }					
				}
		}

	}
	
	protected boolean isMatch(Location location) {
		return location.match(this.c, null);
	}

}
